# -*- coding: utf-8 -*- 

import cPickle as pickle
import time
from config import config
import requests
import json

appid = config['wechat']['appid']
appsecret = config['wechat']['appsecret'] 

def token():
    # Try to open the pickle file
    try:
        f = open('token.pickle', 'rb')
        btoken = pickle.load(f)
        f.close()
    except IOError:
        btoken = {"token":"", "expire":0}
    
    # check if the token is expired and refresh the token
    current_time = int(time.time())
    if btoken['expire'] < current_time:
        btoken = token_get()
        # write token into pickle file
        f = open('token.pickle', 'wb')
        pickle.dump(btoken, f)
    
    # return token value
    return btoken['token']

def token_get():
    params = {
        'grant_type': 'client_credential',
        'appid': appid,
        'secret': appsecret
    }
    r = requests.get("https://api.weixin.qq.com/cgi-bin/token", params = params)
    # print r.text.strip()
    rawtoken = json.loads(r.text.strip())
    current_time = int(time.time())
    btoken = {
        'token': rawtoken['access_token'],
        'expire': current_time + rawtoken['expires_in']
    }
    return btoken

    
        
